package indi.caibo.service_edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import indi.caibo.service_edu.entity.EduChapter;
import indi.caibo.service_edu.entity.EduVideo;
import indi.caibo.service_edu.entity.vo.chapter.ChapterVo;
import indi.caibo.service_edu.entity.vo.video.VideoVo;
import indi.caibo.service_edu.mapper.EduChapterMapper;
import indi.caibo.service_edu.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import indi.caibo.service_edu.service.EduVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Bo Cai
 * @since 2021-10-07
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;

    @Override
    public List<ChapterVo> nestedList(String courseId) {
        List<ChapterVo> chapterVos = new ArrayList<>();
        /*1.获取课时信息*/
        QueryWrapper<EduVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("course_id", courseId);
        videoQueryWrapper.orderByAsc("sort", "id");
        List<EduVideo> eduVideos = videoService.list(videoQueryWrapper);
        /*2.获取章节信息*/
        QueryWrapper<EduChapter> chapterQueryWrapper = new QueryWrapper<>();
        chapterQueryWrapper.eq("course_id", courseId);
        chapterQueryWrapper.orderByAsc("sort", "id");
        List<EduChapter> eduChapters = this.baseMapper.selectList(chapterQueryWrapper);
        /*3.填充vo对象*/
        for (EduChapter chapter : eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter, chapterVo);
            chapterVos.add(chapterVo);
            List<VideoVo> videoVos = new ArrayList<>();
            for (EduVideo video : eduVideos) {
                if (chapter.getId().equals(video.getChapterId())) {
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video, videoVo);
                    videoVos.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVos);
        }
        return chapterVos;
    }

    @Override
    public boolean removeChapterById(String id) {
        Integer result = baseMapper.deleteById(id);
        return null != result && result > 0;
    }

    @Override
    public boolean removeByCourseId(String id) {
        QueryWrapper<EduChapter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", id);
        int count = baseMapper.delete(queryWrapper);
        return count > 0;
    }
}
